import React, { Component } from "react";

// Prompt用于阻止路由跳转的组件
import { Link, Route, Switch, Redirect, Prompt } from "react-router-dom";

class Home extends Component {
  render() {
    return <div>这是home页面</div>;
  }
}
class About extends Component {
  render() {
    return <div>这是about页面</div>;
  }
}
class Form extends Component {
  state = {
    value: "",
  };

  handleChange = (e) => {
    this.setState({
      value: e.target.value,
    });
  };

  render() {
    return (
      <>
        <div>这是表单页面</div>
        <input
          type="text"
          value={this.state.value}
          onChange={this.handleChange}
        />
        {/* when表示什么时候 */}
        {/* message表示询问的时候的提示信息 */}
        {/* when不会做类型转换，必须要用布尔值 */}
        <Prompt
          when={this.state.value !== ""}
          message={(location) =>
            `Are you sure you want to go to ${location.pathname}`
          }
        />
      </>
    );
  }
}

class App extends Component {
  render() {
    return (
      <>
        <h2>react-router-v5-路由保护</h2>
        <ul>
          <li>
            <Link to="/home">首页</Link>
          </li>
          <li>
            <Link to="/about">关于页</Link>
          </li>
          <li>
            <Link to="/form">表单页</Link>
          </li>
        </ul>

        <Switch>
          <Redirect from="/" to="/home" exact></Redirect>
          <Route path="/home" component={Home}></Route>
          <Route path="/about" component={About}></Route>
          <Route path="/form" component={Form}></Route>
        </Switch>
      </>
    );
  }
}

export default App;
